/*
 *  Copyright 2011 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.vcforms.vcapi;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.opu.vcforms.datasource.DataReceiver;
import org.opu.vcforms.datasource.Storage;
import org.opu.vcforms.template.TxtTemplate;
import org.opu.vcforms.transform_t2d.text.Transformer;
import org.opu.vcforms.vcapi.dao.VcTextTemplateDao;
import org.opu.vcforms.vcapi.domain.VcTextTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author yura
 */
public class VcApi {
    public static final String CONTEXT_PATH =
            "classpath:vcapi_applicationcontext.xml";

    private static final String DATA_SOURCE          = "dataSource";
    private static final String SESSION_FACTORY      = "sessionFactory";
    private static final String VC_TEXT_TEMPLATE_DAO = "vcTextTemplateDao";
    private static final String DATA_RECEIVER        = "dataReceiver";

    private ApplicationContext context;
    private HProperties properties;

    private static VcApi instance;

    private VcApi(HProperties properties) {
        this.properties = properties;

        // Before create context we need to determine properties that used in it
        PropertiesMethod.createInstance().replaceAll(properties.toProperties());
        
        this.context = new ClassPathXmlApplicationContext(CONTEXT_PATH);
    }

    public static VcApi newVcApi(HProperties properties){
        if(instance == null){
            return instance = new VcApi(properties);
        } else {
            if (properties == null || instance.properties.equals(properties)){
                return instance;
            } else {
                return instance = new VcApi(properties);
            }
        }
    }

    /**
     * @see #newVcApi(org.opu.vcforms.vcapi.HProperties) 
     * @see HProperties#HProperties(java.util.Properties)
     */
    public static VcApi newVcApi(Properties properties){
        return newVcApi(new HProperties(properties));
    }

    public static VcApi getIinstance(){
        return newVcApi((HProperties)null);
    }

    /**
     * @see #createTextDocument(Integer, Properties, Map)
     */
    public String createTextDocument(Integer templateId)
            throws IOException, UnsupportedOperationException,
            IllegalArgumentException, NullPointerException {
        return createTextDocument(templateId, (Properties) null);
    }

    /**
     * @see #createTextDocument(Integer, Properties, Map)
     */
    public String createTextDocument(Integer templateId, Properties properties)
             throws IOException, UnsupportedOperationException,
             IllegalArgumentException, NullPointerException {
        return createTextDocument(templateId, properties, null);
    }

    /**
     * @see #createTextDocument(Integer, Properties, Map)
     */
    public String createTextDocument(Integer templateId,
            Map<String/* name */, String[][]/* data */> userSettings)
            throws IOException, UnsupportedOperationException,
            IllegalArgumentException, NullPointerException {
        return createTextDocument(templateId, null, userSettings);
    }

    /**
     *
     * @param templateId id of templates in database
     * @param properties settings that can be used in template
     * @param userSettings alternative data source (user customization)<pre>
     *  name of settings and double array of it data:
     *      "Students"
     *          "Ivanov"  "AT-0001"  "5"
     *          "Petrov"  "AT-0001"  "5"
     *          "Sidorov" "AT-0001"  "5"
     *      "Proffessors"
     *          "Preobragenskiy"  "Medic"
     *          "Mozard"          "No"
     * </pre>It's used when not all (or at all all) data taken not from database.
     * @return text document
     * @throws IOException if trouble with parsing template see {@link TxtTemplate#load}
     * @throws UnsupportedOperationException if trouble with creating document by template
     * @throws IllegalArgumentException if trouble with creating document by template
     * @throws NullPointerException if no template by template id
     */
    public String createTextDocument(Integer templateId, Properties properties,
            Map<String/* name */, String[][]/* data */> userSettings)
            throws IOException, UnsupportedOperationException,
            IllegalArgumentException, NullPointerException {

        VcTextTemplateDao tDao = getVcTextTemplateDao();
        VcTextTemplate templateData = tDao.get(templateId);

        TxtTemplate template = new TxtTemplate();
        template.load(new ByteArrayInputStream(templateData.getFileContent()));
        
        DataReceiver dataReceiver = (DataReceiver) context.getBean(DATA_RECEIVER);
        Map<String, Storage> s = toStorageMap(userSettings);

        Transformer transformer = new Transformer(dataReceiver, s, properties);

        return transformer.transform(template);
    }

    public VcTextTemplateDao getVcTextTemplateDao() throws BeansException {
        return (VcTextTemplateDao) context.getBean(VC_TEXT_TEMPLATE_DAO);
    }

    protected Map<String, Storage> toStorageMap(Map<String, String[][]> map){
        Map<String, Storage> smap = new LinkedHashMap<String, Storage>();
        
        for (String name : map.keySet()) {
            Set<Map> set = new LinkedHashSet<Map>();

            for (String[] strings : map.get(name)) {
                Map<String, String> m = new LinkedHashMap<String, String>();

                for (String string : strings) {
                    m.put(string, string);
                }

                set.add(m);
            }

            smap.put(name, new Storage(set));
        }

        return smap;
    }
}
